package net.i4q.sqlved.components;

import java.awt.BorderLayout;
import java.awt.Component;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import net.i4q.sqlved.db.DBConnection;

public class SQLResult extends JPanel {
	private DBConnection dbConnection = new DBConnection();
	private JTable resultTable = null;
	private Component currentComponent;
	
	public SQLResult() {
		
		this.setLayout(new BorderLayout());
	}
	
	public void execute(String sql) {
		try {
			if(currentComponent!=null) {
				this.remove(currentComponent);
			}
			ResultSet rs = dbConnection.getConnection().createStatement().executeQuery(sql);
			
			Vector<String> columnNames = getColumnNames(rs.getMetaData());
			Vector<Vector<String>> data = getData(rs);
			
			DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
			resultTable = new JTable(data, columnNames);
			JScrollPane scrollPane = new JScrollPane(resultTable);
			currentComponent = scrollPane;
			this.add(currentComponent);
			this.doLayout();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Vector<String> getColumnNames(ResultSetMetaData rsMetaData) throws SQLException {
		Vector<String> columnNames = new Vector<String>();
		
		for(int i=0;i<rsMetaData.getColumnCount();i++) {
			columnNames.add(rsMetaData.getColumnName(i+1));
		}
		
		return columnNames;
	}
	
	private Vector<Vector<String>> getData(ResultSet rs) throws SQLException {
		Vector<Vector<String>> data = new Vector<Vector<String>> ();
		
		while(rs.next()) {
			Vector<String> row = new Vector<String>();
			ResultSetMetaData rsMetaData = rs.getMetaData();
			for(int i=0;i<rsMetaData.getColumnCount();i++) {
				row.add(rs.getString(i+1));
			}
			data.add(row);
		}
		
		return data;
	}
	
	public void init(Properties props) throws ClassNotFoundException, SQLException {
		dbConnection.initConnection(props);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame frame  = new JFrame("SQLEditor");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400,100);
		SQLResult sqlResult = new SQLResult();
		frame.add(sqlResult);
		sqlResult.execute("select * from data_dict where domain='Adult' order by sequence");
		frame.setVisible(true);
	}

}
